from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
import time


# 商品表
class FaKuyouGoods(models.Model):
    # 枚举类型选项
    MORE_UNIT_CHOICES = [('1', '是'), ('2', '否')]
    MORE_ATTRIBUTE_CHOICES = [('0', '否'), ('1', '是')]
    STATUS_CHOICES = [('0', '下架'), ('1', '上架')]
    GOODS_TYPE_CHOICES = [('1', '原材料'), ('2', '成品')]
    TAG_CHOICES = ['hot', 'sale']  # SET类型处理

    # 基础信息
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.PositiveIntegerField(null=True, blank=True, verbose_name='管理员ID')
    goods_code = models.CharField(max_length=30, default='', verbose_name='商品编号')
    goods_name = models.CharField(max_length=255, default='', verbose_name='商品名称')
    goods_barcode = models.CharField(max_length=50, default='', blank=True, verbose_name='商品条码')
    goods_specification_id = models.CharField(max_length=50, default='', verbose_name='规格型号')

    # 分类关联
    goods_type_id = models.IntegerField(default=0, verbose_name='商品类别ID')
    manager_warehouse_id = models.IntegerField(default=0, verbose_name='首选仓库ID')

    # 单位信息
    unit_id = models.IntegerField(default=0, verbose_name='计量单位ID')
    more_unit = models.CharField(max_length=1, choices=MORE_UNIT_CHOICES, default='2', verbose_name='多计量单位')
    more_unit_id = models.IntegerField(null=True, blank=True, verbose_name='多单位ID')

    # 价格信息
    market_sell_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='零售价')
    wholesale_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='批发价')
    vip_price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='VIP会员价')
    discount = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                   null=True, blank=True, verbose_name='折扣率1')
    discount2 = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                    null=True, blank=True, verbose_name='折扣率2')
    purchase = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, validators=[MinValueValidator(0)],
                                   null=True, blank=True, verbose_name='预计采购价')

    # 商品展示
    goods_image = models.CharField(max_length=255, default='', verbose_name='商品主图')
    goods_images = models.TextField(null=True, blank=True, verbose_name='商品图集')
    content = models.TextField(null=True, blank=True, verbose_name='商品详情')

    # 库存管理
    inventory = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, verbose_name='总库存')
    more_attribute = models.CharField(max_length=1, choices=MORE_ATTRIBUTE_CHOICES, default='0', null=True, blank=True,
                                      verbose_name='多属性')
    attribute_id = models.CharField(max_length=30, default='', null=True, blank=True, verbose_name='商品属性条码')
    note = models.CharField(max_length=255, default='', verbose_name='备注')

    # 库存预警
    is_offten = models.CharField(max_length=1, choices=[('0', '否'), ('1', '是')], default='0', verbose_name='是否常用')
    stock_warning = models.CharField(max_length=1, choices=[('0', '否'), ('1', '是')], default='0', null=True,
                                     blank=True, verbose_name='库存预警')
    min_stock = models.IntegerField(default=0, null=True, blank=True, verbose_name='最低库存')
    max_stock = models.IntegerField(default=0, null=True, blank=True, verbose_name='最高库存')
    branch = models.CharField(max_length=1, choices=[('0', '否'), ('1', '是')], default='0', null=True, blank=True,
                              verbose_name='分仓预警')

    # 出入库设置
    warehousing = models.IntegerField(null=True, blank=True, verbose_name='首选入库单位')
    warehouse = models.IntegerField(null=True, blank=True, verbose_name='首选出库单位')

    # 期初设置
    period = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True,
                                 verbose_name='期初数量')
    unit_cost = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True,
                                    verbose_name='单位成本')
    price = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True,
                                verbose_name='期初总价')
    period_status = models.CharField(max_length=1, choices=[('0', '未设置'), ('1', '已设置')], default='0', null=True,
                                     blank=True, verbose_name='期初设置')

    # 状态控制
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1', verbose_name='状态')
    is_edit = models.CharField(max_length=1, choices=[('0', '否'), ('1', '是')], default='1', null=True, blank=True,
                               verbose_name='允许修改')

    # 辅助属性
    auxiliary = models.SmallIntegerField(null=True, blank=True, verbose_name='辅助属性设置')
    auxiliary_type = models.CharField(max_length=255, null=True, blank=True, verbose_name='辅助属性')
    auxiliary_type_c = models.CharField(max_length=255, null=True, blank=True, verbose_name='辅助属性2')

    # 批次管理
    batch = models.SmallIntegerField(null=True, blank=True, verbose_name='批次保质期管理')
    shelf_life = models.IntegerField(null=True, blank=True, verbose_name='保质期天数')
    early_warning = models.IntegerField(null=True, blank=True, verbose_name='预警天数')
    serial = models.SmallIntegerField(null=True, blank=True, verbose_name='序列号管理')

    # 标签与销售
    tag = models.CharField(max_length=50, null=True, blank=True, verbose_name='标签')  # 简化SET类型处理
    sale_number = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000, null=True, blank=True,
                                      verbose_name='销量')

    # 业务状态
    order_status = models.CharField(max_length=1, choices=[('0', '不显示'), ('1', '显示')], default='1', null=True,
                                    blank=True, verbose_name='订货通状态')
    goods_type = models.CharField(max_length=1, choices=GOODS_TYPE_CHOICES, default='1', null=True, blank=True,
                                  verbose_name='商品类型')
    promotion = models.CharField(max_length=1, choices=[('0', '否'), ('1', '是')], default='0', null=True, blank=True,
                                 verbose_name='促销状态')

    # 时间戳
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=time.time())
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=time.time())
    deletetime = models.PositiveIntegerField(null=True, blank=True, verbose_name='删除时间')

    class Meta:
        db_table = 'fa_kuyou_goods'
        verbose_name = '商品表'
        verbose_name_plural = '商品表'
        indexes = [
            models.Index(fields=['goods_code']),
            models.Index(fields=['goods_name']),
            models.Index(fields=['goods_type_id']),
        ]

    def __str__(self):
        return f"{self.goods_code} - {self.goods_name}"


# 商品分类表
class FaKuyouGoodsType(models.Model):
    """商品分类表（支持无限级分类）"""
    STATUS_CHOICES = (
        ('0', '禁用'),
        ('1', '正常'),
    )
    ORDER_STATUS_CHOICES = (
        ('0', '不显示'),
        ('1', '显示'),
    )

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    supplier_type_name = models.CharField(
        max_length=120,
        default='',
        verbose_name='分类名称',
        help_text='商品分类名称'
    )
    supplier_type_image = models.CharField(
        max_length=255,
        default='',
        blank=True,
        verbose_name='分类图片',
        help_text='分类图标或封面图'
    )
    pid = models.IntegerField(
        default=0,
        verbose_name='父级ID',
        help_text='0表示一级分类'
    )
    path = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='路径',
        help_text='格式如: 0,1,2 表示三级分类'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='1',
        verbose_name='状态',
        help_text='控制分类是否可用'
    )
    weigh = models.IntegerField(
        default=0,
        validators=[MinValueValidator(0), MaxValueValidator(999)],
        verbose_name='排序权重',
        help_text='数字越大排序越靠前'
    )
    order_status = models.CharField(
        max_length=1,
        choices=ORDER_STATUS_CHOICES,
        default='1',
        verbose_name='订货通显示',
        help_text='是否在订货通显示'
    )
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_goods_type'
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'
        ordering = ['-weigh', 'id']
        indexes = [
            models.Index(fields=['pid'], name='idx_pid'),
            models.Index(fields=['status'], name='idx_status'),
        ]

    def __str__(self):
        return f"{self.supplier_type_name} (ID:{self.id})"

    def save(self, *args, **kwargs):
        self.createtime = int(time.time())
        self.updatetime = int(time.time())

        # 自动生成path路径
        if self.pid == 0:
            self.path = ',0,'
        else:
            try:
                parent = FaKuyouGoodsType.objects.get(pk=self.pid)
                self.path = f",{parent.path},{self.pid},"
            except FaKuyouGoodsType.DoesNotExist:
                self.pid = 0
                self.path = ',0,'

        super().save(*args, **kwargs)

    @classmethod
    def get_tree_data(cls, root_id=0):
        """获取树形结构数据"""
        root = cls.objects.get(pk=root_id) if root_id != 0 else None
        tree = []

        def build_node(node):
            children = node.get_children()
            return {
                'id': node.id,
                'name': node.supplier_type_name,
                'image': node.supplier_type_image,
                'status': node.status,
                'children': [build_node(child) for child in children]
            }

        if root:
            tree.append(build_node(root))
        else:
            for top_node in cls.objects.filter(pid=0, status='1').order_by('-weigh'):
                tree.append(build_node(top_node))

        return tree

    @property
    def level(self):
        """获取分类层级"""
        if not self.path:
            return 1
        return len(self.path.split(','))
